Swift (programming Language)
   HOME

TheInfoList



OR:

Swift is a general-purpose,
multi-paradigm Programming paradigms are a way to classify programming languages based on their features. Languages can be classified into multiple paradigms. Some paradigms are concerned mainly with implications for the execution model of the language, suc ...
,
compiled In computing, a compiler is a computer program that translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primarily used for programs that ...
programming language A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
developed by
Apple Inc. Apple Inc. is an American multinational technology company headquartered in Cupertino, California, United States. Apple is the largest technology company by revenue (totaling in 2021) and, as of June 2022, is the world's biggest company ...
and the open-source community. First released in 2014, Swift was developed as a replacement for Apple's earlier programming language
Objective-C Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTS ...
, as Objective-C had been largely unchanged since the early 1980s and lacked modern language features. Swift works with Apple's
Cocoa Cocoa may refer to: Chocolate * Chocolate * ''Theobroma cacao'', the cocoa tree * Cocoa bean, seed of ''Theobroma cacao'' * Chocolate liquor, or cocoa liquor, pure, liquid chocolate extracted from the cocoa bean, including both cocoa butter and ...
and
Cocoa Touch Cocoa Touch is the application development environment for building software programs to run on iOS for the iPhone and iPod Touch, iPadOS for the iPad, watchOS for the Apple Watch, and tvOS for the Apple TV, from Apple Inc. Cocoa Touch ...
frameworks A framework is a generic term commonly referring to an essential supporting structure which other things are built on top of. Framework may refer to: Computing * Application framework, used to implement the structure of an application for an op ...
, and a key aspect of Swift's design was the ability to interoperate with the huge body of existing Objective-C code developed for Apple products over the previous decades. It was built with the open source
LLVM LLVM is a set of compiler and toolchain technologies that can be used to develop a front end for any programming language and a back end for any instruction set architecture. LLVM is designed around a language-independent intermediate repre ...
compiler In computing, a compiler is a computer program that translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primarily used for programs that ...
framework and has been included in
Xcode Xcode is Apple's integrated development environment (IDE) for macOS, used to develop software for macOS, iOS, iPadOS, watchOS, and tvOS. It was initially released in late 2003; the latest stable release is version 14.2, released on December 13, ...
since version 6, released in 2014. On Apple platforms, it uses the Objective-C
runtime library In computer programming, a runtime library is a set of low-level routines used by a compiler to invoke some of the behaviors of a runtime environment, by inserting calls to the runtime library into compiled executable binary. The runtime enviro ...
, which allows C,
Objective-C Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTS ...
,
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
and Swift code to run within one program. Apple intended Swift to support many core concepts associated with
Objective-C Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTS ...
, notably
dynamic dispatch In computer science, dynamic dispatch is the process of selecting which implementation of a polymorphic operation (method or function) to call at run time. It is commonly employed in, and considered a prime characteristic of, object-oriented ...
, widespread
late binding In computing, late binding or dynamic linkage—though not an identical process to dynamically linking imported code libraries—is a computer programming mechanism in which the method being called upon an object, or the function being called ...
,
extensible programming Extensible programming is a term used in computer science to describe a style of computer programming that focuses on mechanisms to extend the programming language, compiler and runtime environment. Extensible programming languages, supporting this ...
and similar features, but in a "safer" way, making it easier to catch
software bugs A software bug is an error, flaw or fault in the design, development, or operation of computer software that causes it to produce an incorrect or unexpected result, or to behave in unintended ways. The process of finding and correcting bugs i ...
; Swift has features addressing some common
programming error A software bug is an error, flaw or fault in the design, development, or operation of computer software that causes it to produce an incorrect or unexpected result, or to behave in unintended ways. The process of finding and correcting bugs i ...
s like null pointer
dereferencing In computer programming, the dereference operator or indirection operator, sometimes denoted by "*" (i.e. an asterisk), is a unary operator (i.e. one with a single operand) found in List of C-family programming languages, C-like languages that in ...
and provides
syntactic sugar In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an ...
to help avoid the pyramid of doom. Swift supports the concept of
protocol Protocol may refer to: Sociology and politics * Protocol (politics), a formal agreement between nation states * Protocol (diplomacy), the etiquette of diplomacy and affairs of state * Etiquette, a code of personal behavior Science and technolog ...
extensibility, an extensibility system that can be applied to types, structs and classes, which Apple promotes as a real change in programming paradigms they term "protocol-oriented programming" (similar to traits and type classes). Swift was introduced at Apple's 2014 Worldwide Developers Conference (WWDC). It underwent an upgrade to version 1.2 during 2014 and a major upgrade to Swift 2 at WWDC 2015. Initially a proprietary language, version 2.2 was made
open-source software Open-source software (OSS) is computer software that is released under a license in which the copyright holder grants users the rights to use, study, change, and distribute the software and its source code to anyone and for any purpose. Op ...
under the Apache License 2.0 on December 3, 2015, for Apple's platforms and
Linux Linux ( or ) is a family of open-source Unix-like operating systems based on the Linux kernel, an operating system kernel first released on September 17, 1991, by Linus Torvalds. Linux is typically packaged as a Linux distribution, which ...
. Through version 3.0 the syntax of Swift went through significant evolution, with the core team making source stability a focus in later versions. In the first quarter of 2018 Swift surpassed
Objective-C Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTS ...
in measured popularity. Swift 4.0, released in 2017, introduced several changes to some built-in classes and structures. Code written with previous versions of Swift can be updated using the migration functionality built into Xcode. Swift 5, released in March 2019, introduced a stable binary interface on Apple platforms, allowing the Swift runtime to be incorporated into Apple operating systems. It is source compatible with Swift 4. Swift 5.1 was officially released in September 2019. Swift 5.1 builds on the previous version of Swift 5 by extending the stable features of the language to compile-time with the introduction of module stability. The introduction of module stability makes it possible to create and share binary frameworks that will work with future releases of Swift. Swift 5.5, officially announced by Apple at the 2021
WWDC The Worldwide Developers Conference (WWDC) is an information technology conference held annually by Apple Inc. The conference is usually held at Apple Park in California. The event is usually used to showcase new software and technologies in t ...
, significantly expands language support for concurrency and asynchronous code, notably introducing a unique version of the actor model.


History

Development of Swift started in July 2010 by
Chris Lattner Christopher Arthur Lattner (born 1978) is an American software engineer, former Google and Tesla employee and co-founder of LLVM, Clang compiler, MLIR compiler infrastructure and the Swift programming language. , he is the co-founder and CEO ...
, with the eventual collaboration of many other programmers at
Apple An apple is an edible fruit produced by an apple tree (''Malus domestica''). Apple fruit tree, trees are agriculture, cultivated worldwide and are the most widely grown species in the genus ''Malus''. The tree originated in Central Asia, wh ...
. Swift took language ideas "from
Objective-C Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTS ...
,
Rust Rust is an iron oxide, a usually reddish-brown oxide formed by the reaction of iron and oxygen in the catalytic presence of water or air moisture. Rust consists of hydrous iron(III) oxides (Fe2O3·nH2O) and iron(III) oxide-hydroxide (FeO(OH ...
,
Haskell Haskell () is a general-purpose, statically-typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research and industrial applications, Haskell has pioneered a number of programming lan ...
,
Ruby A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sa ...
,
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
, C#, CLU, and far too many others to list". On June 2, 2014, the Apple Worldwide Developers Conference (WWDC) application became the first publicly released app written with Swift. A
beta version A software release life cycle is the sum of the stages of development and maturity for a piece of computer software ranging from its initial development to its eventual release, and including updated versions of the released version to help impro ...
of the
programming language A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
was released to registered Apple developers at the conference, but the company did not promise that the final version of Swift would be
source code In computing, source code, or simply code, is any collection of code, with or without comments, written using a human-readable programming language, usually as plain text. The source code of a program is specially designed to facilitate the wo ...
compatible with the test version. Apple planned to make source code converters available if needed for the full release.Platforms State of the Union, Session 102, Apple Worldwide Developers Conference, June 2, 2014 ''The Swift Programming Language'', a free 500-page manual, was also released at WWDC, and is available on the
Apple Books Apple Books (formerly known as iBooks between January 2010 and September 2018) is an e-book reading and store application by Apple Inc. for its iOS and macOS operating systems and List of iOS devices, devices. It was announced, under the name i ...
Store and the official website. * Swift reached the 1.0 milestone on September 9, 2014, with the ''Gold Master'' of
Xcode Xcode is Apple's integrated development environment (IDE) for macOS, used to develop software for macOS, iOS, iPadOS, watchOS, and tvOS. It was initially released in late 2003; the latest stable release is version 14.2, released on December 13, ...
6.0 for
iOS iOS (formerly iPhone OS) is a mobile operating system created and developed by Apple Inc. exclusively for its hardware. It is the operating system that powers many of the company's mobile devices, including the iPhone; the term also include ...
. Swift 1.1 was released on October 22, 2014, alongside the launch of Xcode 6.1. Swift 1.2 was released on April 8, 2015, along with Xcode 6.3. Swift 2.0 was announced at WWDC 2015, and was made available for publishing apps in the App Store on September 21, 2015. Swift 3.0 was released on September 13, 2016. Swift 4.0 was released on September 19, 2017. Swift 4.1 was released on March 29, 2018. Swift won first place for ''Most Loved Programming Language'' in the
Stack Overflow In software, a stack overflow occurs if the call stack pointer exceeds the stack bound. The call stack may consist of a limited amount of address space, often determined at the start of the program. The size of the call stack depends on many facto ...
Developer Survey 2015 and second place in 2016. On December 3, 2015, the Swift language, supporting libraries, debugger, and package manager were open-sourced under the Apache 2.0 license with a Runtime Library Exception, an
Swift.org
was created to host the project. The source code is hosted o
GitHub
where it is easy for anyone to get the code, build it themselves, and even create pull requests to contribute code back to the project. In December 2015, IBM announced its Swift Sandbox website, which allows developers to write Swift code in one pane and display output in another. The Swift Sandbox was deprecated in January 2018. During the WWDC 2016, Apple announced an
iPad The iPad is a brand of iOS and iPadOS-based tablet computers that are developed by Apple Inc. The iPad was conceived before the related iPhone but the iPhone was developed and released first. Speculation about the development, operating s ...
exclusive app, named
Swift Playgrounds Swift Playgrounds is an educational tool and development environment for the Swift programming language developed by Apple Inc., initially announced at the WWDC 2016 conference. It was introduced as an iPad application alongside iOS 10, with a ...
, intended to teach people how to code in Swift. The app is presented in a 3D video game-like interface which provides feedback when lines of code are placed in a certain order and executed. In January 2017, Chris Lattner announced his departure from Apple for a new position with
Tesla Motors Tesla, Inc. ( or ) is an American multinational automotive and clean energy company headquartered in Austin, Texas. Tesla designs and manufactures electric vehicles (electric cars and trucks), battery energy storage from home to grid- ...
, with the Swift project lead role going to team veteran Ted Kremenek. During WWDC 2019, Apple announced SwiftUI with Xcode 11, which provides a framework for declarative UI structure design across all Apple platforms. Official downloads for the
Ubuntu Ubuntu ( ) is a Linux distribution based on Debian and composed mostly of free and open-source software. Ubuntu is officially released in three editions: '' Desktop'', ''Server'', and ''Core'' for Internet of things devices and robots. All ...
distribution of Linux have been available since Swift 2.2, with more distros added since Swift 5.2.4, CentOS and Amazon Linux. There is an unofficial SDK and native toolchain package for Android too.


Platforms

The platforms Swift supports are Apple's operating systems ( Darwin,
iOS iOS (formerly iPhone OS) is a mobile operating system created and developed by Apple Inc. exclusively for its hardware. It is the operating system that powers many of the company's mobile devices, including the iPhone; the term also include ...
,
iPadOS iPadOS is a mobile operating system developed by Apple Inc. for its iPad line of tablet computers. It is a rebranded variant of iOS, the operating system used by Apple's iPhones, renamed to reflect the diverging features of the two product ...
,
macOS macOS (; previously OS X and originally Mac OS X) is a Unix operating system developed and marketed by Apple Inc. since 2001. It is the primary operating system for Apple's Mac computers. Within the market of desktop and lapt ...
,
tvOS tvOS (formerly known as Apple TV Software) is an operating system developed by Apple Inc. for the Apple TV, a digital media player. In the first-generation Apple TV, Apple TV Software was based on Mac OS X. Starting with the second-generation, ...
,
watchOS watchOS is the operating system of the Apple Watch, developed by Apple Inc. It is based on iOS, the operating system used by the iPhone, and has many similar features. It was released on April 24, 2015, along with the Apple Watch, the only d ...
),
Linux Linux ( or ) is a family of open-source Unix-like operating systems based on the Linux kernel, an operating system kernel first released on September 17, 1991, by Linus Torvalds. Linux is typically packaged as a Linux distribution, which ...
,
Windows Windows is a group of several proprietary graphical operating system families developed and marketed by Microsoft. Each family caters to a certain sector of the computing industry. For example, Windows NT for consumers, Windows Server for serv ...
, and Android.


Version history


Features

Swift is an alternative to the
Objective-C Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTS ...
language that employs modern programming-language theory concepts and strives to present a simpler syntax. During its introduction, it was described simply as "Objective-C without the baggage of C". By default, Swift does not expose pointers and other unsafe accessors, in contrast to Objective-C, which uses pointers pervasively to refer to object instances. Also, Objective-C's use of a
Smalltalk Smalltalk is an object-oriented, dynamically typed reflective programming language. It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Ka ...
-like syntax for making method calls has been replaced with a dot-notation style and
namespace In computing, a namespace is a set of signs (''names'') that are used to identify and refer to objects of various kinds. A namespace ensures that all of a given set of objects have unique names so that they can be easily identified. Namespaces ...
system more familiar to programmers from other common
object-oriented Object-oriented programming (OOP) is a programming paradigm based on the concept of " objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of p ...
(OO) languages like
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
or C#. Swift introduces true
named parameter In computer programming, named parameters, named argument or keyword arguments refer to a computer language's support for function calls that clearly state the name of each parameter within the function call. Overview A function call using na ...
s and retains key Objective-C concepts, including
protocols Protocol may refer to: Sociology and politics * Protocol (politics), a formal agreement between nation states * Protocol (diplomacy), the etiquette of diplomacy and affairs of state * Etiquette, a code of personal behavior Science and technology ...
, closures and
categories Category, plural categories, may refer to: Philosophy and general uses *Categorization, categories in cognitive science, information science and generally *Category of being * ''Categories'' (Aristotle) *Category (Kant) * Categories (Peirce) * ...
, often replacing former syntax with cleaner versions and allowing these concepts to be applied to other language structures, like
enumerated type In computer programming, an enumerated type (also called enumeration, enum, or factor in the R programming language, and a categorical variable in statistics) is a data type consisting of a set of named values called ''elements'', ''members'', '' ...
s (enums).


Closure support

Swift supports closures (known as lambdas in other languages). Closures are self-contained blocks of functionality that can be passed around and used in code, and can also be used as
anonymous function In computer programming, an anonymous function (function literal, lambda abstraction, lambda function, lambda expression or block) is a function definition that is not bound to an identifier. Anonymous functions are often arguments being passed to ...
s. Here are some examples: // Closure type, defined by its input and output values, can be specified outside the closure: let closure1: (Int, Int) -> Int = // …or inside it: let closure2 = // In most cases, closure's return type can be inferred automatically by the compiler. // However, this functionality may not work for too complex expressions. let closure3 = Swift also has a trailing closure syntax which looks like this: // This function takes a closure which receives no input parameters and returns an integer, // evaluates it, and uses the closure's return value (an Int) as the function's return value. func foo(closure bar: () -> Int) -> Int // Without trailing closure syntax: foo(closure: ) // With trailing closure syntax: foo Starting from version 5.3, Swift supports multiple trailing closures: // This function passes the return of the first closure as the parameter of the second, // and returns the second closure's result: func foo(bar: () -> Int, baz: (Int) -> Int) -> Int // With no trailing closures: foo(bar: , baz: ) // With 1 trailing closure: foo(bar: ) // With 2 trailing closures (note that only the first closure's argument name is omitted): foo baz: Here are the criteria for the trailing closure syntax: * If the last arguments of a function are closures, one can use the trailing closure syntax. * The parameter name of the first trailing closure must be omitted. * The parameter names of the remaining trailing closures must not be omitted. * If all the arguments given to a function are trailing closures, the parentheses after the function's name can be omitted. * Calls to a function with trailing closures must be parenthesized if used in a guard statement.


String support

Under the
Cocoa Cocoa may refer to: Chocolate * Chocolate * ''Theobroma cacao'', the cocoa tree * Cocoa bean, seed of ''Theobroma cacao'' * Chocolate liquor, or cocoa liquor, pure, liquid chocolate extracted from the cocoa bean, including both cocoa butter and ...
and
Cocoa Touch Cocoa Touch is the application development environment for building software programs to run on iOS for the iPhone and iPod Touch, iPadOS for the iPad, watchOS for the Apple Watch, and tvOS for the Apple TV, from Apple Inc. Cocoa Touch ...
environments, many common classes were part of the
Foundation Kit The Foundation Kit, or just Foundation for short, is an Objective-C framework in the OpenStep specification. It provides basic classes such as wrapper classes and data structure classes. This framework uses the prefix NS (for NeXTSTEP). It is a ...
library. This included the NSString string library (using
Unicode Unicode, formally The Unicode Standard,The formal version reference is is an information technology Technical standard, standard for the consistent character encoding, encoding, representation, and handling of Character (computing), text expre ...
,
UTF-8 UTF-8 is a variable-width encoding, variable-length character encoding used for electronic communication. Defined by the Unicode Standard, the name is derived from ''Unicode'' (or ''Universal Coded Character Set'') ''Transformation Format 8-bit'' ...
in Swift 5, changed from
UTF-16 UTF-16 (16-bit Unicode Transformation Format) is a character encoding capable of encoding all 1,112,064 valid code points of Unicode (in fact this number of code points is dictated by the design of UTF-16). The encoding is variable-length, as cod ...
), the NSArray and NSDictionary collection classes, and others. Objective-C provided various bits of
syntactic sugar In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an ...
to allow some of these objects to be created on-the-fly within the language, but once created, the objects were manipulated with object calls. For instance, in Objective-C concatenating two NSStrings required method calls similar to this: NSString *str = @"hello,"; str = tr stringByAppendingString:@" world" In Swift, many of these basic types have been promoted to the language's core, and can be manipulated directly. For instance, strings are invisibly bridged to NSString (when Foundation is imported) and can now be concatenated with the + operator, allowing greatly simplified syntax; the prior example becoming: var str = "hello," str += " world"


Access control

Swift supports five access control levels for symbols: , , , , and . Unlike many object-oriented languages, these access controls ignore
inheritance Inheritance is the practice of receiving private property, Title (property), titles, debts, entitlements, Privilege (law), privileges, rights, and Law of obligations, obligations upon the death of an individual. The rules of inheritance differ ...
hierarchies: indicates that a symbol is accessible only in the immediate
scope Scope or scopes may refer to: People with the surname * Jamie Scope (born 1986), English footballer * John T. Scopes (1900–1970), central figure in the Scopes Trial regarding the teaching of evolution Arts, media, and entertainment * Cinem ...
, indicates it is accessible only from within the file, indicates it is accessible within the containing module, indicates it is accessible from any module, and (only for classes and their methods) indicates that the class may be subclassed outside of the module.


Optionals and chaining

An important new feature in Swift is
option type In programming languages (especially functional programming languages) and type theory, an option type or maybe type is a polymorphic type that represents encapsulation of an optional value; e.g., it is used as the return type of functions whic ...
s, which allow references or values to operate in a manner similar to the common pattern in C, where a pointer may refer to a value or may be null. This implies that non-optional types cannot result in a null-pointer error; the compiler can ensure this is not possible. Optional types are created with the Optional mechanism—to make an Integer that is nullable, one would use a declaration similar to var optionalInteger: Optional. As in C#, Swift also includes syntactic sugar for this, allowing one to indicate a variable is optional by placing a question mark after the type name, var optionalInteger: Int?. Variables or constants that are marked optional either have a value of the underlying type or are nil. Optional types ''wrap'' the base type, resulting in a different instance. String and String? are fundamentally different types, the latter has more in common with Int? than String. To access the value inside, assuming it is not nil, it must be ''unwrapped'' to expose the instance inside. This is performed with the ! operator: let myValue = anOptionalInstance!.someMethod() In this case, the ! operator unwraps anOptionalInstance to expose the instance inside, allowing the method call to be made on it. If anOptionalInstance is nil, a null-pointer error occurs. This can be annoying in practice, so Swift also includes the concept of optional chaining to test whether the instance is nil and then unwrap it if it is non-null: let myValue = anOptionalInstance?.someMethod() In this case the runtime calls someMethod only if anOptionalInstance is not nil, suppressing the error. Normally this requires the programmer to test whether myValue is nil before proceeding. The origin of the term ''chaining'' comes from the more common case where several method calls/getters are chained together. For instance: let aTenant = aBuilding.tenantList let theirLease = aTenant.leaseDetails let leaseStart = theirLease?.startDate can be reduced to: let leaseStart = aBuilding.tenantList leaseDetails?.startDate The ? syntax circumvents the pyramid of doom. Swift 2 introduced the new keyword guard for cases in which code should stop executing if some condition is unmet: guard let leaseStart = aBuilding.TenantList .leaseDetails?.startDate else //continue, knowing that leaseStart is not nil Using guard has three benefits. While the syntax can act as an if statement, its primary benefit is inferring non-nullability. Where an if statement requires a case, guard assumes the case based on the condition provided. Also, since guard contains no scope, with exception of the else closure, leaseStart is presented as an unwrapped optional to the guard's super-scope. Lastly, if the guard statement's test fails, Swift requires the else to exit the current method or loop, ensuring leaseStart never is accessed when nil. This is performed with the keywords return, continue, break, or throw, or by calling a function returning a Never (e.g. fatalError()). Objective-C was weakly typed and allowed any method to be called on any object at any time. If the method call failed, there was a default handler in the runtime that returned nil. That meant that no unwrapping or testing was needed, the equivalent statement in Objective-C: leaseStart = [aBuilding_tenantList:5leaseDetails.html" ;"title="Building_tenantList:5.html" ;"title="[aBuilding tenantList:5">[aBuilding tenantList:5leaseDetails">Building_tenantList:5.html" ;"title="[aBuilding tenantList:5">[aBuilding tenantList:5leaseDetailsstartDate] Would return nil, and this could be tested. However, this also demanded that all method calls be dynamic, which introduces significant overhead. Swift's use of optionals provides a similar mechanism for testing and dealing with nils, but does so in a way that allows the compiler to use static dispatch because the unwrapping action is called on a defined instance (the wrapper), versus occurring in the runtime dispatch system.


Value types

In many object-oriented languages, objects are represented internally in two parts. The object is stored as a block of data placed on the heap, while the name (or "handle") to that object is represented by a pointer. Objects are passed between methods by copying the value of the pointer, allowing the same underlying data on the heap to be accessed by anyone with a copy. In contrast, basic types like integers and floating-point values are represented directly; the handle contains the data, not a pointer to it, and that data is passed directly to methods by copying. These styles of access are termed ''pass-by-reference'' in the case of objects, and ''pass-by-value'' for basic types. Both concepts have their advantages and disadvantages. Objects are useful when the data is large, like the description of a window or the contents of a document. In these cases, access to that data is provided by copying a 32- or 64-bit value, versus copying an entire data structure. However, smaller values like integers are the same size as pointers (typically both are one
word A word is a basic element of language that carries an semantics, objective or pragmatics, practical semantics, meaning, can be used on its own, and is uninterruptible. Despite the fact that language speakers often have an intuitive grasp of w ...
), so there is no advantage to passing a pointer, versus passing the value. Also, pass-by-reference inherently requires a dereferencing operation, which can produce noticeable overhead in some operations, typically those used with these basic value types, like mathematics. Similarly to C# and in contrast to most other OO languages, Swift offers built-in support for objects using either pass-by-reference or pass-by-value semantics, the former using the class declaration and the latter using struct. Structs in Swift have almost all the same features as classes: methods, implementing protocols and using the extension mechanisms. For this reason, Apple terms all data generically as ''instances'', versus objects or values. Structs do not support inheritance, however. The programmer is free to choose which semantics are more appropriate for each data structure in the application. Larger structures like windows would be defined as classes, allowing them to be passed around as pointers. Smaller structures, like a 2D point, can be defined as structs, which will be pass-by-value and allow direct access to their internal data with no dereference. The performance improvement inherent to the pass-by-value concept is such that Swift uses these types for almost all common data types, including Int and Double, and types normally represented by objects, like String and Array. Using value types can result in significant performance improvements in user applications as well. To ensure that even the largest structs do not cause a performance penalty when they are handed off, Swift uses
copy on write Copy-on-write (COW), sometimes referred to as implicit sharing or shadowing, is a resource-management technique used in computer programming to efficiently implement a "duplicate" or "copy" operation on modifiable resources. If a resource is dupl ...
so that the objects are copied only if and when the program attempts to change a value in them. This means that the various accessors have what is in effect a pointer to the same data storage. So while the data is physically stored as one instance in memory, at the level of the application, these values are separate and physical separation is enforced by copy on write only if needed.


Protocol-oriented programming

A key feature of Objective-C is its support for ''categories'', methods that can be added to extend classes at runtime. Categories allow extending classes in-place to add new functions with no need to subclass or even have access to the original
source code In computing, source code, or simply code, is any collection of code, with or without comments, written using a human-readable programming language, usually as plain text. The source code of a program is specially designed to facilitate the wo ...
. An example might be to add spell checker support to the base NSString class, which means all instances of NSString in the application gain spell checking. The system is also widely used as an organizational technique, allowing related code to be gathered into library-like extensions. Swift continues to support this concept, although they are now termed ''extensions'', and declared with the keyword extension. Unlike Objective-C, Swift can also add new properties accessors, types, and enums to extant instances . Another key feature of Objective-C is its use of ''protocols'', known in most modern languages as ''interfaces''. Protocols promise that a particular class implements a set of methods, meaning that other objects in the system can call those methods on any object supporting that protocol. This is often used in modern OO languages as a substitute for
multiple inheritance Multiple inheritance is a feature of some object-oriented computer programming languages in which an object or class can inherit features from more than one parent object or parent class. It is distinct from single inheritance, where an object or ...
, although the feature sets are not entirely similar. A common example of a protocol in Cocoa is the NSCopying protocol, which defines one method, copyWithZone, that implements deep copying on objects. In Objective-C, and most other languages implementing the protocol concept, it is up to the programmer to ensure that the required methods are implemented in each class. Swift adds the ability to add these methods using extensions, and to use
generic programming Generic programming is a style of computer programming in which algorithms are written in terms of types ''to-be-specified-later'' that are then ''instantiated'' when needed for specific types provided as parameters. This approach, pioneered b ...
(generics) to implement them. Combined, these allow protocols to be written once and support a wide variety of instances. Also, the extension mechanism can be used to add protocol conformance to an object that does not list that protocol in its definition. For example, a protocol might be declared called StringConvertible, which ensures that instances that conform to the protocol implement a toString method that returns a String. In Swift, this can be declared with code like this: protocol StringConvertible This protocol can now be added to String, with no access to the base class's source: extension String: StringConvertible In Swift, like many modern languages supporting interfaces, protocols can be used as types, which means variables and methods can be defined by protocol instead of their specific type: var someSortOfPrintableObject: StringConvertible ... print(someSortOfPrintableObject.toString()) It does not matter what sort of instance someSortOfPrintableObject is, the compiler will ensure that it conforms to the protocol and thus this code is safe. This syntax also means that collections can be based on protocols also, like let printableArray = tringConvertible/code>. As Swift treats structs and classes as similar concepts, both extensions and protocols are extensively used in Swift's runtime to provide a rich API based on structs. For instance, Swift uses an extension to add the Equatable protocol to many of their basic types, like Strings and Arrays, allowing them to be compared with the

operator. A concrete example of how all of these features interact can be seen in the concept of ''default protocol implementations'': func !=(lhs: T, rhs: T) -> Bool This function defines a method that works on any instance conforming to Equatable, providing a ''not equals'' function. Any instance, class or struct, automatically gains this implementation simply by conforming to Equatable. As many instances gain Equatable through their base implementations or other generic extensions, most basic objects in the runtime gain equals and not equals with no code. This combination of protocols, defaults, protocol inheritance, and extensions allows many of the functions normally associated with classes and inheritance to be implemented on value types. Properly used, this can lead to dramatic performance improvements with no significant limits in API. This concept is so widely used within Swift that Apple has begun calling it a ''protocol-oriented programming language''. They suggest addressing many of the problem domains normally solved through classes and inheritance using protocols and structs instead.


Libraries, runtime and development

On Apple systems, Swift uses the same runtime as the extant
Objective-C Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTS ...
system, but requires iOS 7 or macOS 10.9 or higher. It also depends on
Grand Central Dispatch Grand Central Dispatch (GCD or libdispatch), is a technology developed by Apple Inc. to optimize application support for systems with multi-core processors and other symmetric multiprocessing systems. It is an implementation of task paralleli ...
. Swift and Objective-C code can be used in one program, and by extension, C and C++ also. In contrast to C,
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
code cannot be used directly from Swift. An Objective-C or C wrapper must be created between Swift and C++. In the case of Objective-C, Swift has considerable access to the object model, and can be used to subclass, extend and use Objective-C code to provide protocol support. The converse is not true: a Swift class cannot be subclassed in Objective-C. To aid development of such programs, and the re-use of extant code, Xcode 6 and higher offers a semi-automated system that builds and maintains a ''bridging header'' to expose Objective-C code to Swift. This takes the form of an additional
header file Many programming languages and other computer files have a directive, often called include (sometimes copy or import), that causes the contents of the specified file to be inserted into the original file. These included files are called copybooks ...
that simply defines or imports all of the Objective-C symbols that are needed by the project's Swift code. At that point, Swift can refer to the types, functions, and variables declared in those imports as though they were written in Swift. Objective-C code can also use Swift code directly, by importing an automatically maintained header file with Objective-C declarations of the project's Swift symbols. For instance, an Objective-C file in a mixed project called "MyApp" could access Swift classes or functions with the code #import "MyApp-Swift.h". Not all symbols are available through this mechanism, however—use of Swift-specific features like generic types, non-object optional types, sophisticated enums, or even Unicode identifiers may render a symbol inaccessible from Objective-C. Swift also has limited support for ''attributes'', metadata that is read by the development environment, and is not necessarily part of the compiled code. Like Objective-C, attributes use the @ syntax, but the currently available set is small. One example is the @IBOutlet attribute, which marks a given value in the code as an ''outlet'', available for use within
Interface Builder Interface Builder is a software development application for Apple's macOS operating system. It is part of Xcode (formerly Project Builder), the Apple Developer developer's toolset. Interface Builder allows Cocoa and Carbon developers to creat ...
(IB). An ''outlet'' is a device that binds the value of the on-screen display to an object in code. On non-Apple systems, Swift does not depend on an Objective-C runtime or other Apple system libraries; a set of Swift "Corelib" implementations replace them. These include a "swift-corelibs-foundation" to stand in for the
Foundation Kit The Foundation Kit, or just Foundation for short, is an Objective-C framework in the OpenStep specification. It provides basic classes such as wrapper classes and data structure classes. This framework uses the prefix NS (for NeXTSTEP). It is a ...
, a "swift-corelibs-libdispatch" to stand in for the Grand Central Dispatch, and an "swift-corelibs-xctest" to stand in for the XCTest APIs from
Xcode Xcode is Apple's integrated development environment (IDE) for macOS, used to develop software for macOS, iOS, iPadOS, watchOS, and tvOS. It was initially released in late 2003; the latest stable release is version 14.2, released on December 13, ...
. As of 2019, with Xcode 11, Apple has also added a major new UI paradigm called SwiftUI. SwiftUI replaces the older
Interface Builder Interface Builder is a software development application for Apple's macOS operating system. It is part of Xcode (formerly Project Builder), the Apple Developer developer's toolset. Interface Builder allows Cocoa and Carbon developers to creat ...
paradigm with a new declarative development paradigm.


Memory management

Swift uses
Automatic Reference Counting Automatic Reference Counting (ARC) is a memory management feature of the Clang compiler providing automatic reference counting for the Objective-C and Swift programming languages. At compile time, it inserts into the object code messages retain a ...
(ARC) to manage memory. Apple used to require manual memory management in Objective-C, but introduced ARC in 2011 to allow for easier memory allocation and deallocation. One problem with ARC is the possibility of creating a '' strong reference cycle'', where objects reference each other in a way that you can reach the object you started from by following references (e.g. A references B, B references A). This causes them to become leaked into memory as they are never released. Swift provides the keywords weak and unowned to prevent strong reference cycles. Typically a parent-child relationship would use a strong reference while a child-parent would use either weak reference, where parents and children can be unrelated, or unowned where a child always has a parent, but parent may not have a child. Weak references must be optional variables, since they can change and become nil. A closure within a class can also create a strong reference cycle by capturing self references. Self references to be treated as weak or unowned can be indicated using a ''capture list.''


Debugging and other elements

A key element of the Swift system is its ability to be cleanly debugged and run within the development environment, using a
read–eval–print loop A read–eval–print loop (REPL), also termed an interactive toplevel or language shell, is a simple interactive computer programming environment that takes single user inputs, executes them, and returns the result to the user; a program written ...
(REPL), giving it interactive properties more in common with the scripting abilities of Python than traditional
system programming Systems programming, or system programming, is the activity of programming computer system software. The primary distinguishing characteristic of systems programming when compared to application programming is that application programming aims to pr ...
languages. The REPL is further enhanced with
playgrounds A playground, playpark, or play area is a place designed to provide an environment for children that facilitates play, typically outdoors. While a playground is usually designed for children, some are designed for other age groups, or people w ...
, interactive views running within the Xcode environment that respond to code or debugger changes on-the-fly. Playgrounds allow programmers to add in Swift code along with markdown documentation. If some code changes over time or with regard to some other ranged input value, the view can be used with the Timeline Assistant to demonstrate the output in an animated way. In addition, Xcode has debugging features for Swift development including breakpoints, step through and step over statements, as well as UI element placement breakdowns for app developers. Apple says that Swift is "an industrial-quality programming language that's as expressive and enjoyable as a scripting language".


Performance

Many of the features introduced with Swift have well-known performance and safety trade-offs. Apple has implemented optimizations that reduce this overhead.


Comparisons to other languages

Swift is considered a C family programming language and is similar to C in various ways: * Most C operators are used in Swift, but there are some new operators, for example to support integer operations with overflow (see under differences). *
Curly braces A bracket is either of two tall fore- or back-facing punctuation marks commonly used to isolate a segment of text or data from its surroundings. Typically deployed in symmetric pairs, an individual bracket may be identified as a 'left' or 'r ...
are used to group statements. * Variables are assigned using an
equals sign The equals sign (British English, Unicode) or equal sign (American English), also known as the equality sign, is the mathematical symbol , which is used to indicate equality in some well-defined sense. In an equation, it is placed between two ...
, but compared using two consecutive equals signs. A new identity operator,

, is provided to check if two data elements refer to the same
object Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an ...
. * Control statements while, if, and switch are similar, but have extended functions, e.g., a switch that takes non-integer cases, while and if supporting
pattern matching In computer science, pattern matching is the act of checking a given sequence of tokens for the presence of the constituents of some pattern. In contrast to pattern recognition, the match usually has to be exact: "either it will or will not be ...
and conditionally unwrapping optionals, for uses the syntax. *
Square brackets A bracket is either of two tall fore- or back-facing punctuation marks commonly used to isolate a segment of text or data from its surroundings. Typically deployed in symmetric pairs, an individual bracket may be identified as a 'left' or 'r ...
are used with
arrays An array is a systematic arrangement of similar objects, usually in rows and columns. Things called an array include: {{TOC right Music * In twelve-tone and serial composition, the presentation of simultaneous twelve-tone sets such that the ...
, both to declare them and to get a value at a given index in one of them. It also has similarities to Objective-C: * Basic numeric types (Int, UInt, Float, Double) * Class methods are inherited, like instance methods; self in class methods is the class the method was called on. * Similar for...in enumeration syntax. Differences from Objective-C include: * Statements do not need to end with semicolons (;), though these must be used to allow more than one statement on a line. * No header files. * Uses
type inference Type inference refers to the automatic detection of the type of an expression in a formal language. These include programming languages and mathematical type systems, but also natural languages in some branches of computer science and linguistics ...
. *
Generic programming Generic programming is a style of computer programming in which algorithms are written in terms of types ''to-be-specified-later'' that are then ''instantiated'' when needed for specific types provided as parameters. This approach, pioneered b ...
. * Functions are first-class objects. * Enumeration cases can have associated data (
algebraic data type In computer programming, especially functional programming and type theory, an algebraic data type (ADT) is a kind of composite type, i.e., a type formed by combining other types. Two common classes of algebraic types are product types (i.e., ...
s). * Operators can be redefined for classes (
operator overloading In computer programming, operator overloading, sometimes termed ''operator ad hoc polymorphism'', is a specific case of polymorphism, where different operators have different implementations depending on their arguments. Operator overloading i ...
), and new operators can be defined. * Strings fully support
Unicode Unicode, formally The Unicode Standard,The formal version reference is is an information technology Technical standard, standard for the consistent character encoding, encoding, representation, and handling of Character (computing), text expre ...
. Most Unicode characters can be used in either identifiers or operators. * No
exception handling In computing and computer programming, exception handling is the process of responding to the occurrence of ''exceptions'' – anomalous or exceptional conditions requiring special processing – during the execution of a program. In general, an ...
. Swift 2 introduces a different and incompatible error-handling model. * Several features of earlier C-family languages that are easy to misuse have been removed: **
Pointers Pointer may refer to: Places * Pointer, Kentucky * Pointers, New Jersey * Pointers Airport, Wasco County, Oregon, United States * The Pointers, a pair of rocks off Antarctica People with the name * Pointer (surname), a surname (including a lis ...
are not exposed by default. There is no need for the programmer to keep track of and mark names for referencing or dereferencing. ** Assignments return no value. This prevents the common error of writing i = 0 instead of i

0
by throwing a compile-time error. ** No need to use break statements in
switch In electrical engineering, a switch is an electrical component that can disconnect or connect the conducting path in an electrical circuit, interrupting the electric current or diverting it from one conductor to another. The most common type of ...
blocks. Individual cases do not fall through to the next case unless the fallthrough statement is used. ** Variables and constants are always initialized and array bounds are always checked. **
Integer overflow In computer programming, an integer overflow occurs when an arithmetic operation attempts to create a numeric value that is outside of the range that can be represented with a given number of digits – either higher than the maximum or lower ...
s, which result in
undefined behavior In computer programming, undefined behavior (UB) is the result of executing a program whose behavior is prescribed to be unpredictable, in the language specification to which the computer code adheres. This is different from unspecified behavior ...
for signed integers in C, are trapped as a run-time error in Swift. Programmers can choose to allow overflows by using the special arithmetical operators &+, &-, &*, &/ and &%. The properties min and max are defined in Swift for all integer types and can be used to safely check for potential overflows, versus relying on constants defined for each type in external libraries. ** The one-statement form of if and while, which allows for the omission of braces around the statement, is unsupported. ** C-style enumeration for (int i = 0; i < c; i++), which is prone to
off-by-one error An off-by-one error or off-by-one bug (known by acronyms OBOE, OBO, OB1 and OBOB) is a logic error involving the discrete equivalent of a boundary condition. It often occurs in computer programming when an iterative loop iterates one time too m ...
s, is unsupported (from Swift 3 onward). ** The pre- and post- increment and decrement operators (i++, --i ...) are unsupported (from Swift 3 onward), more so since C-style for statements are also unsupported from Swift 3 onward.


Development and other implementations

Since the language is open-source, there are prospects of it being ported to the web. Some web frameworks have already been developed, such as IBM's Kitura, Perfect and
Vapor In physics, a vapor (American English) or vapour (British English and Canadian English; see spelling differences) is a substance in the gas phase at a temperature lower than its critical temperature,R. H. Petrucci, W. S. Harwood, and F. G. Her ...
. An official "Server APIs" work group has also been started by Apple, with members of the Swift developer community playing a central role. A second free implementation of Swift that targets
Cocoa Cocoa may refer to: Chocolate * Chocolate * ''Theobroma cacao'', the cocoa tree * Cocoa bean, seed of ''Theobroma cacao'' * Chocolate liquor, or cocoa liquor, pure, liquid chocolate extracted from the cocoa bean, including both cocoa butter and ...
,
Microsoft Microsoft Corporation is an American multinational technology corporation producing computer software, consumer electronics, personal computers, and related services headquartered at the Microsoft Redmond campus located in Redmond, Washing ...
's Common Language Infrastructure ( .NET), and the
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
and Android platform exists as part of the ''Elements Compiler'' from
RemObjects Software RemObjects Software is an American software company founded in 2002 by Alessandro Federici and Marc Hoffman. It develops and offers tools and libraries for software developers on a variety of development platforms, including Embarcadero Delphi, M ...
. By combining
toolchain In software, a toolchain is a set of programming tools that is used to perform a complex software development task or to create a software product, which is typically another computer program or a set of related programs. In general, the tools for ...
s from LLVM and
Macintosh Programmer's Workshop Macintosh Programmer's Workshop (MPW) is a software development environment for the Classic Mac OS operating system, written by Apple Computer. For Macintosh developers, it was one of the primary tools for building applications for System 7.x an ...
, it is possible to run a very small subset of the language on Mac OS 9.


See also

*
Comparison of programming languages Programming languages are used for controlling the behavior of a machine (often a computer). Like natural languages, programming languages follow the rules for syntax and semantics. There are thousands of programming languages and new ones are c ...
*
Objective-C Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTS ...
*
Kotlin (programming language) Kotlin () is a cross-platform software, cross-platform, static typing, statically typed, general-purpose programming language, general-purpose programming language with type inference. Kotlin is designed to interoperate fully with Java (programm ...
*
Python (programming language) Python is a high-level, general-purpose programming language. Its design philosophy emphasizes code readability with the use of significant indentation. Python is dynamically-typed and garbage-collected. It supports multiple programming para ...
*
Nim (programming language) Nim is a general-purpose, multi-paradigm, statically typed, compiled systems programming language, designed and developed by a team around Andreas Rumpf. Nim is designed to be "efficient, expressive, and elegant", supporting metaprogramming, ...


References


External links

*
Swift
at
Apple Developer Apple Developer (formerly Apple Developer Connection) is Apple Inc.'s website for software development tools, application programming interfaces (APIs), and technical resources. It contains resources to help software developers write software for ...
*
Swift Example

Server-side Swift - The Vapor Framework
{{Authority control Apple Inc. software Computer-related introductions in 2014 Object-oriented programming languages Pattern matching programming languages Programming languages Programming languages created in 2014 Software using the Apache license Statically typed programming languages Systems programming languages Declarative programming